Java后端避坑

您所在的位置:网站首页 apiparam 多个参数 Java后端避坑

Java后端避坑

2023-11-01 01:33| 来源: 网络整理| 查看: 265

今天在项目中书写分页接口的时候,在Controller层和dao层分别用了@RequestParam和@Param这两个注解。简单说一下对这两个注解的理解。

@RequestParam:

一般用在Controller层,用来解决前端与后端参数不一致的问题,在参数上加上@RequestParam,那么前端的参数必须和后端参数一致,否则会报错。当只有一个参数的时候,Controller层中@RequestParam和@Param可以互用,当有多个参数的时候,Controller层中@RequestParam和@Param不能互用

示例程序如下: @GetMapping("/") public RespPageBean getAllEmployeeByPage(@RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "10")Integer size){ return salaryService.getAllEmployeeByPage(page,size); }

另一个作用是指定Value或name的参数名,或者指定参数是否必传 ####该注解的底层代码如下:

@Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface RequestParam { @AliasFor("name") String value() default ""; @AliasFor("value") String name() default ""; boolean required() default true; String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n"; } @Param:

一般用在dao层,用来给参数命名,在Mybatis的mapper中加上该注解,传递的参数与Sql中的字段名一致。

示例程序如下: List getAllEmployeeByPage(@Param("page") Integer page, @Param("size") Integer size); 该注解的底层代码如下: @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) public @interface Param { String value(); }

笔者测试了一下将上面程序中的@Param注解更换为@RequestParam,程序编译没有报错,但是点击前端页面的分页组件时,出现了如下错误:

2019-04-25 21:23:48.703 ERROR 9148 --- [nio-8082-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'page' not found. Available parameters are [arg1, arg0, param1, param2]] with root cause org.apache.ibatis.binding.BindingException: Parameter 'page' not found. Available parameters are [arg1, arg0, param1, param2]

错误代码示例如下: List getAllEmployeeByPage(@RequestParam("page") Integer page, @RequestParam("size") Integer size);

建议在书写代码的时候,保持良好的书写习惯,不随意书写代码,便能避开很多不必要的坑!

积少成多,滴水穿石!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3